package com.example.demo.service;

import com.example.demo.GoodsJPARepository;
import com.example.demo.entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.awt.print.Pageable;
import java.util.ArrayList;
import java.util.List;

@Service
public abstract class GoodsService {
    @Autowired
    GoodsJPARepository goodsRepository;

    public Goods addGoods(Goods good){return goodsRepository.saveAndFlush(good);}

    public Goods getGoods(long id){return goodsRepository.getReferenceById(id);}

    public void updateGoods(long id,Goods good){
        goodsRepository.save(good);}

    public void deleteGoods(long id){
        goodsRepository.deleteById(id);}

    public List<Goods> findGoods(String name, Integer amount, Double price){
        Specification<Goods> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> predicateList = new ArrayList<>();
            if (name != null) {
                predicateList.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
            }
            if ((amount != null)) {
                predicateList.add(criteriaBuilder.like(root.get("amount"), "%"+amount+"%"));
            }
            if(price!=null){
                predicateList.add(criteriaBuilder.equal(root.get("price"),price));
            }
            Predicate[] predicates = predicateList.toArray(new Predicate[predicateList.size()]);
            return criteriaBuilder.and(predicates);
        };

        List<Goods> result= goodsRepository.findAll(specification);
        return result;
    }

    public abstract Page<Goods>findByName(String name, Pageable pageable);

}